package com.wuercloud.mq.message.listener;

import com.rabbitmq.client.Channel;
import com.wuercloud.mq.common.ResultRes;
import com.wuercloud.mq.message.consumer.ConsumerSubject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by JiangWL on 2017/3/30.
 */
@Component
public class MessageHandlerListener implements ChannelAwareMessageListener {

    @Autowired
    private ConsumerSubject consumerSubject;
    private static Logger logger = LoggerFactory.getLogger(MessageHandlerListener.class);
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        logger.info("onMessage:"+message);
        String messageStr = new String(message.getBody());
        String routingKey = message.getMessageProperties().getReceivedRoutingKey();
        logger.info("当前收到的信息所属："+routingKey+"队列。");
        ResultRes result = consumerSubject.nodifyObservers(routingKey,messageStr);//由业务处理返回
        if(result.isSuccess()){
            //channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);//true代表确认所有consumer获得的消息；此处应为false,只确认当前一个消息收到
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            logger.info("完成ack:"+channel);
        }else{
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            logger.info("完成Nack,重新入队Reject:"+channel);
        }
    }
}
